package com.example.lib_network.manager

import android.util.Log
import com.example.lib_framework.utils.NetworkUtil
import com.example.lib_network.constant.BASE_URL
import com.example.lib_network.error.ERROR
import com.example.lib_network.error.NoNetWorkException
import com.example.lib_network.interceptor.CookiesInterceptor
import com.example.lib_network.interceptor.HeaderInterceptor
import com.sum.framework.helper.SumAppHelper
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import java.util.concurrent.TimeUnit

/**
 *
 * @Description TODO
 * @Author Bohemian
 * @CreateTime 2024/01/19/ 20:17
 */
object HttpManager {
    private val mRetrofit: Retrofit
    init {
        mRetrofit=Retrofit.Builder()
            .client(initOkHttpClient())
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    /**
     * 获取 apiService
     */
    fun <T> create(apiService:Class<T>):T{
        return mRetrofit.create(apiService)
    }
    /**
     * 初始化OkHttp
     */
    private fun initOkHttpClient():OkHttpClient{
        val build=OkHttpClient.Builder()
            .connectTimeout(12, TimeUnit.SECONDS)
            .writeTimeout(12, TimeUnit.SECONDS)
            .readTimeout(12, TimeUnit.SECONDS)
        // 添加多个参数拦截器
        val interceptors = mutableListOf<Interceptor>()
        build.addInterceptor(CookiesInterceptor())
        build.addInterceptor(HeaderInterceptor())
        //日志拦截器
        val logInterceptor = HttpLoggingInterceptor { message: String ->
            Log.i("okhttp", "data:$message")
        }
        build.addInterceptor(logInterceptor)
        //此处是判断环境切换打印日志类型
        if (SumAppHelper.isDebug()) {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.BASIC
        }
        build.addInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                if (NetworkUtil.isConnected(SumAppHelper.getApplication())) {
                    val request = chain.request()
                    return chain.proceed(request)
                } else {
                    throw NoNetWorkException(ERROR.NETWORD_ERROR)
                }
            }
        })
        return build.build()
    }
}